package com.github.lee.unsplash.utils

import androidx.lifecycle.MutableLiveData
import com.github.lee.mvvm.core.vm.BaseViewModel
import com.github.lee.unsplash.domain.response.BaseResult
import com.github.lee.mvvm.core.vm.exceptions.ResponseThrowable
import com.github.lee.mvvm.core.vm.exceptions.resultIsNull
import com.github.lee.mvvm.core.vm.exceptions.unknownError
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

fun <T> BaseViewModel.requestForResult(
    block: suspend CoroutineScope.() -> T?,
    success: suspend CoroutineScope.(T) -> Unit,
    error: suspend CoroutineScope.(Throwable) -> Unit,
) {
    launchOnUI {
        withContext(Dispatchers.IO) {
            try {
                val result = block()
                if (null == result) {
                    throw resultIsNull()
                } else {
                    success(result)
                }
            } catch (t: Throwable) {
                error(t)
            }
        }
    }
}
//
//fun <T> BaseViewModel.requestForSuccess(
//    block: suspend CoroutineScope.() -> BaseResult<T>?,
//    success: suspend CoroutineScope.(T) -> Unit,
//) {
//    requestForResult(
//        block = {
//            block() ?: throw resultIsNull()
//        },
//        success = {
//            if (!it.isSuccess()) {
//                val code = it.code
//                val msg = it.msg
//                throw ResponseThrowable(code, msg)
//            } else {
//                success(it.data)
//            }
//        },
//        error = {
//            if (it is ResponseThrowable) {
//                throwableLiveData.postValue(it)
//            } else {
//                val msg = it.message ?: "Unknown Mistake"
//                throwableLiveData.postValue(unknownError(msg))
//            }
//        }
//    )
//}